package com.ruoyi.com.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.com.mapper.ComDeptMenuMapper;
import com.ruoyi.com.mapper.ComMenuMapper;
import com.ruoyi.com.mapper.ComUserMapper;
import com.ruoyi.com.service.IComMenuService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.OperateBasicForm;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.ComMenu;
import com.ruoyi.common.core.domain.entity.ComMenu;
import com.ruoyi.common.core.domain.entity.ComMenu;
import com.ruoyi.common.core.domain.entity.ComUser;
import com.ruoyi.common.core.domain.model.LoginUnitfUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.com.domain.ComDeptMenu;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.vo.MetaVo;
import com.ruoyi.system.domain.vo.RouterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 公共菜单Service业务层处理
 *
 * @author sunye
 * @date 2024-09-26
 */
@Service
public class ComMenuServiceImpl extends ServiceImpl<ComMenuMapper, ComMenu> implements IComMenuService
{

    @Value("${system.parentMenuId}")
    String parentMenuId;

    @Autowired
    private ComMenuMapper menuMapper;


    @Autowired
    private ComUserMapper comUserMapper;

    @Autowired
    private ComDeptMenuMapper comDeptMenuMapper;

    @Override
    public List<ComMenu> selectMenuTreeByUserId(LoginUnitfUser loginUser) {
        List<ComMenu> menus = null;
        Long userId = loginUser.getUserId();
        Long deptId = loginUser.getDeptId();
        if (loginUser.getUser().getIsAdmin()==1)
        {
            menus = menuMapper.selectMenuTreeAll(deptId,parentMenuId);
        }
        else
        {
            //查询该用户下的部门绑定的角色 和用户本身绑定的角色
            List<Long> roleIds =comUserMapper.selectAllRoleIdsByUserId(userId,deptId);
            if(roleIds == null ||roleIds.size() == 0){
                throw new ServiceException("该用户没有绑定角色，请联系管理员！");
            }
            Long[] roleArray = roleIds.toArray(new Long[0]);
            menus = menuMapper.selectMenuTreeByUserId(roleArray,deptId,parentMenuId);
        }
        return getChildPerms(menus, Integer.parseInt(parentMenuId));
    }

    @Override
    public  List<RouterVo>  buildMenus(List<ComMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (ComMenu menu : menus)
        {
            RouterVo router = new RouterVo();
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(),false, menu.getPath()));
            List<ComMenu> cMenus = menu.getChildren();
            if (StringUtils.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType()))
            {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            }
            else if (isMenuFrame(menu))
            {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(getRouteName(null, menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(),false, menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            else if (menu.getParentId().intValue() == Integer.parseInt(parentMenuId) && isInnerLink(menu))
            {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(getRouteName(null, routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    @Override
    public List<ComMenu> selectMenuList(LoginUnitfUser loginUser) {
        return selectMenuList(new ComMenu(), loginUser);
    }

    @Override
    public List<Long> selectMenuListByRoleId(Long roleId) {
        return menuMapper.selectMenuListByRoleId(roleId);
    }

    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<ComMenu> menus) {
        List<ComMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public String selectMenuNameById(String parentMenuId) {
        return menuMapper.selectMenuNameById(parentMenuId);
    }

    @Override
    public List<ComMenu> selectUserHaveSmall(ComUser user, Long deptId) {
        Long isAdmin = user.getIsAdmin();
        Long userId = user.getUserId();
        String type = user.getType();
        List<ComMenu> list = new ArrayList<>();
        if(isAdmin==1){
            //管理员获取小程序列表
            //小程序系统
            list =  comDeptMenuMapper.selectXcxBaseListByDeptId("1",deptId);
//            if("1".equals(type)){
//                //小程序系统
//                list =  comDeptMenuMapper.selectXcxBaseListByDeptId(type,deptId);
//            }else if("2".equals(type)){
//                //数字商城后台系统
//                list = comDeptMenuMapper.selectShopXcxListByDeptId(type,deptId);
//            }else if("3".equals(type)){
//                //数字商城商家系统
//                list = comDeptMenuMapper.selectShopXcxListByDeptId(type,deptId);
//            }
        }else{
            //查询该用户下的部门绑定的角色 和用户本身绑定的角色
            List<Long> roleIds =comUserMapper.selectAllRoleIdsByUserId(userId,deptId);
            if(roleIds == null ||roleIds.size() == 0){
                throw new ServiceException("该用户没有绑定角色，请联系管理员！");
            }
            Long[] roleId = roleIds.toArray(new Long[0]);
            //获取小程序列表
            //小程序系统
            list =  comDeptMenuMapper.selectXcxMenuListByRoleIds(roleId);
//            if("1".equals(type)){
//                //小程序系统
//                list =  comDeptMenuMapper.selectXcxMenuListByRoleIds(roleId);
//            }else if("2".equals(type)){
//                //数字商城后台系统
//                list = comDeptMenuMapper.selectShopAdminMenuListByRoleIds(roleId);
//            }else if("3".equals(type)){
//                //数字商城商家系统
//                list = comDeptMenuMapper.selectShopSellMenuListByRoleIds(roleId);
//            }
        }
        return list;
    }


    public List<ComMenu> buildMenuTree(List<ComMenu> menus)
    {
        List<ComMenu> returnList = new ArrayList<ComMenu>();
        List<Long> tempList = menus.stream().map(ComMenu::getMenuId).collect(Collectors.toList());
        for (Iterator<ComMenu> iterator = menus.iterator(); iterator.hasNext();)
        {
            ComMenu menu = (ComMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId()))
            {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }


    public List<ComMenu> selectMenuList(ComMenu menu, LoginUnitfUser loginUser) {
        List<ComMenu> menuList = null;
        // 管理员显示所有菜单信息
        ComUser comUser = loginUser.getUser();
        Long deptId = loginUser.getDeptId();
        if (comUser != null && 1==comUser.getIsAdmin())
        {
            menuList = menuMapper.selectMenuTreeAll(deptId,parentMenuId);
        }
        else
        {
            //查询该用户下的部门绑定的角色 和用户本身绑定的角色
            List<Long> roleIds =comUserMapper.selectAllRoleIdsByUserId(comUser.getUserId(),deptId);
            if(roleIds == null ||roleIds.size() == 0){
                throw new ServiceException("该用户没有绑定角色，请联系管理员！");
            }
            Long[] roleArray = roleIds.toArray(new Long[0]);
            menuList = menuMapper.selectMenuTreeByUserId(roleArray,deptId,parentMenuId);
        }
        return menuList;
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<ComMenu> getChildPerms(List<ComMenu> list, int parentId)
    {
        List<ComMenu> returnList = new ArrayList<ComMenu>();
        for (Iterator<ComMenu> iterator = list.iterator(); iterator.hasNext();)
        {
            ComMenu t = (ComMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t 子节点
     */
    private void recursionFn(List<ComMenu> list, ComMenu t)
    {
        // 得到子节点列表
        List<ComMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ComMenu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ComMenu> getChildList(List<ComMenu> list, ComMenu t)
    {
        List<ComMenu> tlist = new ArrayList<ComMenu>();
        Iterator<ComMenu> it = list.iterator();
        while (it.hasNext())
        {
            ComMenu n = (ComMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ComMenu> list, ComMenu t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path)
    {
        return StringUtils.replaceEach(path, new String[] { Constants.HTTP, Constants.HTTPS, Constants.WWW, ".", ":" },
                new String[] { "", "", "", "/", "/" });
    }


    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(ComMenu menu)
    {
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            return StringUtils.EMPTY;
        }
        return getRouteName(null, menu.getPath());
    }

    /**
     * 获取路由名称，如没有配置路由名称则取路由地址
     *
     * @param path 路由地址
     * @return 路由名称（驼峰格式）
     */
    public String getRouteName(String name, String path)
    {
        String routerName = StringUtils.isNotEmpty(name) ? name : path;
        return StringUtils.capitalize(routerName);
    }


    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(ComMenu menu)
    {
        return menu.getParentId().intValue() == Integer.parseInt(parentMenuId) && UserConstants.TYPE_MENU.equals(menu.getMenuType());
    }


    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(ComMenu menu)
    {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != Integer.parseInt(parentMenuId) && isInnerLink(menu))
        {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (Integer.parseInt(parentMenuId) == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType()))
        {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(ComMenu menu)
    {
        return StringUtils.ishttp(menu.getPath());
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(ComMenu menu)
    {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu))
        {
            component = menu.getComponent();
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != Integer.parseInt(parentMenuId) && isInnerLink(menu))
        {
            component = UserConstants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu))
        {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(ComMenu menu)
    {
        return menu.getParentId().intValue() != Integer.parseInt(parentMenuId) && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }
}
